<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="geender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in stuList" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.geender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      stuList: [
        {
          id: 1,
          name: "战三",
          age: 12,
          geender: "男",
        },
        {
          id: 2,
          name: "李思思",
          age: 12,
          geender: "女",
        },
      ],
      id: "",
      name: "",
      age: "",
      geender: "",
      flag: true,
    };
  },
  methods: {
    add() {
      if (!this.name || !this.age || !this.geender) {
        alert("参数不能为空");
        return;
      }
      if (this.flag) {
        this.id = this.stuList.length
          ? this.stuList[this.stuList.length - 1].id + 1
          : 1;
        this.stuList.push({
          id: this.id,
          name: this.name,
          age: this.age,
          geender: this.geender,
        });
      } else {
        this.flag = true;
        this.$set(this.stuList, this.id - 1, {
          id: this.id,
          name: this.name,
          age: this.age,
          geender: this.geender,
        });
      }
      // 清空列表
      this.id = "";
      this.name = "";
      this.age = "";
      this.geender = "";
    },
    edit(i) {
      this.flag = false;
      //返回好像是vue对象
      let obj = this.stuList[i];
      this.id = obj.id;
      this.name = obj.name;
      this.age = obj.age;
      this.geender = obj.geender;
    },
    del(i) {
      this.stuList.splice(i, 1);
    },
  },
};
</script>